<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>错题本 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            danger: '#F53F3F',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            'option-hover': '#F1F5F9',
            'option-selected': '#E6F0FF',
            'error-bg': '#FFF1F0'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-6 py-3 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80 font-medium;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-collect {
        @apply flex items-center gap-1 text-gray-500 hover:text-accent transition-colors px-2 py-1 text-sm;
      }
      .option-item {
        @apply flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-colors hover:bg-option-hover border border-transparent;
      }
      .option-item.selected {
        @apply bg-option-selected border-primary/30;
      }
      .option-item.correct {
        @apply bg-green-50 border-green-200;
      }
      .option-item.incorrect {
        @apply bg-error-bg border-danger/20;
      }
      .answer-feedback {
        @apply mt-6 p-4 rounded-lg;
      }
      .feedback-correct {
        @apply bg-green-50 border border-green-200 text-green-800;
      }
      .feedback-incorrect {
        @apply bg-error-bg border border-danger/20 text-danger;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors relative">
            <i class="fa fa-bell-o"></i>
            <span class="absolute -top-1 -right-1 w-4 h-4 bg-accent text-white text-xs rounded-full flex items-center justify-center">3</span>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">李同学</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 (默认隐藏) -->
      <nav id="teacher-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 -->
      <nav id="student-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <!-- 错题练习头部信息 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">错题本练习</h2>
            <p class="text-gray-500 mt-1">从你的错题中随机抽取1题，连续做对2次以上将移除该题</p>
          </div>

          <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4">
            <div class="flex items-center gap-2">
              <i class="fa fa-question-circle text-danger"></i>
              <span class="text-sm">总错题数：{{ num }} 题</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 错题练习说明 -->
      <div class="bg-error-bg border border-danger/20 rounded-xl p-4 mb-6">
        <div class="flex items-start">
          <i class="fa fa-lightbulb-o text-danger mt-0.5 mr-3"></i>
          <div class="text-sm">
            <p class="font-medium text-danger">错题巩固规则</p>
            <p class="text-gray-700 mt-1">• 系统从你的错题库中随机抽取1题进行练习</p>
            <p class="text-gray-700">• 每道题连续做对2次以上，将自动从错题本中移除</p>
            <p class="text-gray-700">• 做错的题目会继续保留在错题本中，等待下次练习</p>
            <p class="text-gray-700">• 提交后可查看答案</p>
          </div>
        </div>
      </div>

      <!-- 题目容器 -->
      <div class="space-y-8 mb-10" id="question-container">
        <!-- 题目将通过JS动态渲染 -->
        <div class="flex items-center justify-center py-10">
          <i class="fa fa-spinner fa-spin text-primary text-2xl mr-2"></i>
          <span class="text-gray-500">加载题目中...</span>
        </div>
      </div>

      <!-- 按钮区域 -->
      <div class="flex flex-col sm:flex-row gap-4 justify-center mb-10" id="button-group" style="display: none;">
        <button id="submit-btn" class="btn-primary flex-1 sm:flex-none min-w-[150px] justify-center items-center">
          <i class="fa fa-check mr-2"></i>提交答案
        </button>
        <button id="next-btn" class="btn-secondary flex-1 sm:flex-none min-w-[150px] justify-center items-center">
          <i class="fa fa-arrow-right mr-2"></i>下一题
        </button>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4 mt-auto">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

  <script>
    // 全局变量：当前题目ID、学生ID、用户答案、是否已提交
    async function UserIdInfo(){
        try{
            const response = await fetch('/api/current-user');
            const userid = await response.json();
            return userid
        }
        catch (error){
            console.error('加载用户信息失败：',error);
        }
    }
    const STU_ID = UserIdInfo().username; // 实际项目中应从登录态获取
    let currentQuestionId = null;
    let userAnswer = null;
    let isSubmitted = false;
    var exam_id = null
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
      setupRoleSwitch();
      setupEventListeners();
      loadNewQuestion(); // 页面打开时加载第一题
    });

    // 设置事件监听器
    const setupEventListeners = () => {
      // 提交答案按钮
      document.getElementById('submit-btn').addEventListener('click', submitAnswer);

      // 下一题按钮
      document.getElementById('next-btn').addEventListener('click', loadNewQuestion);
    };

    // 角色切换功能
    const setupRoleSwitch = () => {
      const teacherTab = document.getElementById('teacher-tab');
      const studentTab = document.getElementById('student-tab');
      const teacherNav = document.getElementById('teacher-nav');
      const studentNav = document.getElementById('student-nav');


      studentTab.addEventListener('click', () => {
        studentTab.classList.add('bg-primary', 'text-white');
        studentTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        teacherTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        teacherTab.classList.remove('bg-primary', 'text-white');
        studentNav.classList.remove('hidden');
        teacherNav.classList.add('hidden');
      });
    };

    // 加载新题目
    const loadNewQuestion = async () => {
      try {
        const container = document.getElementById('question-container');
        // 显示加载状态
        container.innerHTML = `
          <div class="flex items-center justify-center py-10">
            <i class="fa fa-spinner fa-spin text-primary text-2xl mr-2"></i>
            <span class="text-gray-500">加载题目中...</span>
          </div>
        `;

        // 调用后端接口获取新题目
        const response = await fetch(`/new_question/${STU_ID}`);
        const question = await response.json();
        exam_id = question.data.exam_id
        if (!question.success) {
          throw new Error('获取题目失败');
        }
        renderQuestion(question.data);
      } catch (error) {
        console.error('加载题目出错:', error);
        document.getElementById('question-container').innerHTML = `
          <div class="bg-error-bg border border-danger/20 rounded-xl p-4 text-danger text-center">
            <i class="fa fa-exclamation-triangle mr-2"></i>加载题目失败，请稍后重试
          </div>
        `;
      }
    };

    // 格式化选项（A、B、C、D...）
    const formatOptionLabel = (index) => {
      return String.fromCharCode(65 + index); // 65是'A'的ASCII码
    };

    // 渲染题目
    const renderQuestion = (question) => {
    const container = document.getElementById('question-container');
    const buttonGroup = document.getElementById('button-group');
    currentQuestionId = question.id;
    isSubmitted = false;
    userAnswer = null;

    container.innerHTML = '';
    buttonGroup.style.display = 'flex';

    // 题目基础结构
    const questionCard = document.createElement('div');
    questionCard.className = 'bg-white rounded-xl p-6 card-shadow';

    // 题目头部（题号+题型）
    const questionHeader = document.createElement('div');
    questionHeader.className = 'flex items-center justify-between mb-4';
    questionHeader.innerHTML = `
      <span class="text-sm font-medium text-primary bg-primary/10 px-3 py-1 rounded-full">题号：${question.id}</span>
      <span class="text-sm font-medium text-gray-500">${question.type}</span>
    `;
    questionCard.appendChild(questionHeader);

    // 题目内容
    const questionTitle = document.createElement('div');
    questionTitle.className = 'text-lg font-medium mb-6';
    questionTitle.textContent = question.title;
    questionCard.appendChild(questionTitle);

    // 关键修改：解析 option（JSON字符串 -> 数组）
    let options = [];
    if (question.option) {
      try {
        // 1. 解析 JSON 字典（如 {"A": "27", "B": "26", ...}）
        const optionDict = JSON.parse(question.option);
        // 2. 提取选项（按 A/B/C/D 顺序）
        // 先获取字典的键（如 ["A", "B", "C", "D"]）
        const keys = Object.keys(optionDict);
        // 按字母顺序排序（确保A在前，B在后）
        keys.sort();
        // 提取对应的值作为选项数组
        options = keys.map(key => optionDict[key]);
      } catch (e) {
        console.error('解析选项失败：', e);
        const errorDiv = document.createElement('div');
        errorDiv.className = 'text-danger text-sm mb-6';
        errorDiv.textContent = '题目选项格式错误，请联系管理员';
        questionCard.appendChild(errorDiv);
      }
    }

  // 根据题型渲染选项/输入框（使用解析后的 options 数组）
  switch(question.type) {
    case '选择题':
      renderSingleChoice(questionCard, options);  // 传入解析后的数组
      break;
    case '多选题':
      renderMultipleChoice(questionCard, options);  // 传入解析后的数组
      break;
    case '填空题':
      renderFillBlank(questionCard);
      break;
    case '简答题':
      renderEssay(questionCard);
      break;
  }

  container.appendChild(questionCard);
};

    // 渲染单选题
    const renderSingleChoice = (parent, options) => {
      const optionsContainer = document.createElement('div');
      optionsContainer.className = 'space-y-2 mb-6';

      options.forEach((option, index) => {
        const optionItem = document.createElement('div');
        optionItem.className = 'option-item';
        optionItem.dataset.value = formatOptionLabel(index);

        optionItem.innerHTML = `
          <div class="w-5 h-5 rounded-full border border-gray-300 flex items-center justify-center text-sm">
            ${formatOptionLabel(index)}
          </div>
          <span>${option}</span>
        `;

        // 选择逻辑
        optionItem.addEventListener('click', () => {
          if (isSubmitted) return;
          // 清除其他选项的选中状态
          document.querySelectorAll('.option-item').forEach(item => {
            item.classList.remove('selected');
          });
          // 设置当前选项为选中
          optionItem.classList.add('selected');
          userAnswer = optionItem.dataset.value;
        });

        optionsContainer.appendChild(optionItem);
      });

      parent.appendChild(optionsContainer);
    };

    // 渲染多选题
    const renderMultipleChoice = (parent, options) => {
      const optionsContainer = document.createElement('div');
      optionsContainer.className = 'space-y-2 mb-6';
      userAnswer = [];

      options.forEach((option, index) => {
        const optionItem = document.createElement('div');
        optionItem.className = 'option-item';
        optionItem.dataset.value = formatOptionLabel(index);

        optionItem.innerHTML = `
          <div class="w-5 h-5 border border-gray-300 flex items-center justify-center text-sm">
            <i class="fa fa-check text-primary hidden"></i>
          </div>
          <span>${option}</span>
        `;

        // 选择逻辑
        optionItem.addEventListener('click', () => {
          if (isSubmitted) return;

          const checkIcon = optionItem.querySelector('i');
          const value = optionItem.dataset.value;

          if (optionItem.classList.contains('selected')) {
            // 取消选择
            optionItem.classList.remove('selected');
            checkIcon.classList.add('hidden');
            userAnswer = userAnswer.filter(item => item !== value);
          } else {
            // 选中
            optionItem.classList.add('selected');
            checkIcon.classList.remove('hidden');
            userAnswer.push(value);
          }
        });

        optionsContainer.appendChild(optionItem);
      });

      parent.appendChild(optionsContainer);
    };

    // 渲染填空题
    const renderFillBlank = (parent) => {
      const inputContainer = document.createElement('div');
      inputContainer.className = 'mb-6';

      const input = document.createElement('textarea');
      input.className = 'w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors';
      input.rows = 3;
      input.placeholder = '请输入答案...';

      input.addEventListener('input', (e) => {
        if (!isSubmitted) {
          userAnswer = e.target.value;
        }
      });

      inputContainer.appendChild(input);
      parent.appendChild(inputContainer);
    };

    // 渲染简答题
    const renderEssay = (parent) => {
      const inputContainer = document.createElement('div');
      inputContainer.className = 'mb-6';

      const textarea = document.createElement('textarea');
      textarea.className = 'w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors';
      textarea.rows = 5;
      textarea.placeholder = '请输入答案...';

      textarea.addEventListener('input', (e) => {
        if (!isSubmitted) {
          userAnswer = e.target.value;
        }
      });

      inputContainer.appendChild(textarea);
      parent.appendChild(inputContainer);
    };

    // 提交答案
    const submitAnswer = async () => {
      if (isSubmitted) return;
      if (userAnswer === null || userAnswer === undefined ||
          (Array.isArray(userAnswer) && userAnswer.length === 0) ||
          (typeof userAnswer === 'string' && userAnswer.trim() === '')) {
        alert('请先选择或输入答案');
        return;
      }

      try {
        // 构建提交数据
        const submitData = {
          question_id: currentQuestionId,
          student_id: STU_ID,
          answer: userAnswer,
          exam_id:exam_id
        };

        // 调用提交答案接口
        const response = await fetch('/submit_answer', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(submitData)
        });

        const result = await response.json()

        if (!result.success) {
          console.log(result.error)
          throw new Error('提交答案失败');
        }

        displayAnswerResult(result.data);
        isSubmitted = true;
      } catch (error) {
        console.error('提交答案出错:', error);
        alert('提交答案失败，请稍后重试');
      }
    };

    // 显示答案结果
    const displayAnswerResult = (result) => {
      const questionCard = document.querySelector('#question-container .card-shadow');

      // 创建结果反馈区域
      const feedbackContainer = document.createElement('div');
      feedbackContainer.className = 'answer-feedback';

      // 根据得分设置反馈样式
      if (result.student_score == result.score) {
        feedbackContainer.classList.add('feedback-correct');
        feedbackContainer.innerHTML = `
          <div class="flex items-center mb-2">
            <i class="fa fa-check-circle mr-2"></i>
            <h3 class="font-medium">回答正确</h3>
          </div>
          <p class="text-sm">得分：${result.student_score}</p>
          <p class="text-sm mt-2"><strong>参考答案：</strong>${formatAnswer(result.correct_answer)}</p>
        `;
      } else {
        feedbackContainer.classList.add('feedback-incorrect');
        feedbackContainer.innerHTML = `
          <div class="flex items-center mb-2">
            <i class="fa fa-times-circle mr-2"></i>
            <h3 class="font-medium">回答错误</h3>
          </div>
          <p class="text-sm">得分：${result.student_score}</p>
          <p class="text-sm mt-2"><strong>你的答案：</strong>${formatAnswer(userAnswer)}</p>
          <p class="text-sm mt-2"><strong>参考答案：</strong>${formatAnswer(result.correct_answer)}</p>
        `;
      }

      // 添加到题目卡片中
      questionCard.appendChild(feedbackContainer);

      // 处理选项的正确/错误显示（针对选择题）
      const questionType = document.querySelector('.text-gray-500').textContent;
      if (questionType === '选择题' || questionType === '多选题') {
        highlightOptions(result.correct_answer);
      }
    };

    // 格式化答案显示
    const formatAnswer = (answer) => {
      if (Array.isArray(answer)) {
        return answer.join(', ');
      }
      return answer || '无';
    };

    // 高亮显示正确/错误的选项（针对选择题）
    const highlightOptions = (correctAnswer) => {
      const options = document.querySelectorAll('.option-item');
      const correctAnswers = Array.isArray(correctAnswer) ? correctAnswer : [correctAnswer];
      const userAnswers = Array.isArray(userAnswer) ? userAnswer : [userAnswer];

      options.forEach(option => {
        const value = option.dataset.value;

        // 移除之前的选中样式
        option.classList.remove('selected');

        // 标记正确选项
        if (correctAnswers.includes(value)) {
          option.classList.add('correct');
          // 在正确选项上添加对勾标记
          const iconContainer = option.querySelector('div:first-child');
          iconContainer.innerHTML += '<i class="fa fa-check text-secondary ml-1"></i>';
        }
        // 标记错误选择的选项
        else if (userAnswers.includes(value)) {
          option.classList.add('incorrect');
          // 在错误选项上添加叉号标记
          const iconContainer = option.querySelector('div:first-child');
          iconContainer.innerHTML += '<i class="fa fa-times text-danger ml-1"></i>';
        }
      });
    };
  </script>
</body>
</html>